<?php
/**
 * 分发类
 *
 * @copyright	http://www.easymvc.com
 * @author 		光哥  <439884988@qq.com>
 * @version		1.0 - 2012-03-26
 * @package		Frame
 */

class Frame_Dispatcher {
	public static $app= 'www';
	public static $fileName = 'Index';
	public static $Controller = '_Controller_';
	public static $control;
	public static $action = 'home';
	public static $control_obj;
	public static $plugins = array();
	public static $alias;
	
	public static function init(){
	}
	
    /**
     * 插件
     * @param unknown_type $queue_execute
     * @param unknown_type $plugin_obj
     */
	public static function add_plugin($plugin_obj){
		$plugin_name = get_class($plugin_obj);
		self::$plugins[$plugin_name]	= $plugin_obj;
	}
	/*
	 * 运行插件
	 * 
	 */
	public static function run_plugin(){
		foreach(self::$plugins as $plugin_obj) {
			$plugin_obj->run();
		}
	}
	/*
	 * 分发
	 */
	public static function dispatch(){
		self::route();
		self::execute();
	}
	/*
	 * 路由url
	*/
	public static function route(){
		switch(URL_RULE) {
			case 'path': self::urlPath();
			break;
			default : self::urlNormal();
		}
	}
	
	/*
	 * 执行
	 */
	public static function execute(){
		if(!class_exists(self::$control)){
			throw new Frame_Exception_Program(self::$control ." class no exist" );
		}
		$class = new ReflectionClass(self::$control);
		self::$control_obj = $class->newInstance();
		if(!method_exists(self::$control_obj,self::$action)) {
			throw new Frame_Exception_Program("class ".self::$control.' method '.self::$action." no exist" );
		}
		self::run_plugin();
		$class->getMethod(self::$action)->invoke(self::$control_obj);
	}
	
	
	/**
	 * 正常url模式 index.php?app=blog&d=ajax&f=index
	 */
	public static function urlNormal(){
		if(ALIAS) {
			$app =  strstr($_SERVER['SERVER_NAME'], '.', true);
		}else{
			$app = isset($_GET['app']) ? ucfirst($_GET['app']) : '';
		}
		$d = isset($_GET['d']) ? ucfirst($_GET['d']) : '';
		$f = isset($_GET['f']) ? ucfirst($_GET['f']) : '';
		if($app){
			$d = $d ? $d."_" : '';
			$f = $f ? $f : self::$fileName;
				
			self::$control = $app.self::$Controller.$d.$f;
		}else{
			self::$control = self::$app.self::$Controller.self::$fileName;
				
		}
			
	}
	/**
	 * url path 模式
	 */
	public static function urlPath(){
		if(ALIAS) {
			$alias =  strstr($_SERVER['SERVER_NAME'], '.', true);
			$_SERVER['PATH_INFO'] = $alias.$_SERVER['PATH_INFO'];
		}
		$url = isset($_SERVER['PATH_INFO']) ? trim($_SERVER['PATH_INFO'],'/') : '';
		@list($app,$d,$f) = array_map("ucfirst",explode('/',$url));
		if($app){
			if($f) {
				$f = '_'.$f;
			}else{
				$f = $d ? $d : self::$fileName;
				$d = '';
			}
			self::$control = $app.self::$Controller.$d.$f;
		}else{
			self::$control = self::$app.self::$Controller.self::$fileName;
				
		}
	}
	
	
}

?>